'use client'
import React, { use, useEffect, useState } from 'react'
import PageTitle from '@/components/admin/common/PageTitle';
import { useRouter } from 'next/navigation';
import request from '@/utils/request';
import message from '@/components/common/message';
import { isEqual } from 'lodash';
import Loading from '@/components/common/Loading';
import SuperInput from '@/components/admin/common/SuperInput';
import SuperCheckbox from '@/components/admin/common/SuperCheckbox';
import SuperSelect from '@/components/admin/common/SuperSelect';
import ImageUpload from '@/components/admin/common/ImageUpload';

export default function Atricle({ params }) {
  const { id } = use(params);
  const [loaded, setLoaded] = useState(false);
  const [originBlog, setOriginBlog] = useState(null);
  const [blog, setBlog] = useState(null);
  const router = useRouter();
  const [changed, setChanged] = useState(false);

  const saveBlogValues = () => {
    if (!changed) {
      router.back();
    } else {
      request(`/api/admin/blogs`, { method: 'PUT', body: JSON.stringify(blog), headers: { 'Content-Type': 'application/json' } })
        .then((res) => {
          if (res.code === 0) {
            message.success('保存成功');
            fetchBlog(id);
          } else {
            message.error(res.codeMap(res.code));
          }
        })
    }
  }

  const fetchBlog = async (id) => {
    request(`/api/admin/blogs/${id}`)
      .then((res) => {
        if (res.code === 0) {
          setOriginBlog(res.data);
          setBlog(res.data);
          setLoaded(true);
        } else {
          message.error(res.codeMap[res.code]);
        }
      })
  }

  useEffect(() => {
    fetchBlog(id);
  }, [id]);

  const resetBlog = () => {
    setBlog(originBlog);
  }

  const changeHandle = (key, value) => {
    setBlog(prev => { return { ...prev, [key]: value } });
  }

  useEffect(() => {
    const isChange = !isEqual(originBlog, blog);
    setChanged(isChange);
  }, [blog, originBlog]);

  const content = (
    <div>
      <PageTitle title={`${blog?.title} - 编辑`} extraButtonText={changed ? '重置' : ''} onExtraButtonClick={resetBlog} buttonText={changed ? '保存' : "返回上一页"} onButtonClick={saveBlogValues} />
      <div className='mx-auto rounded-xs shadow-xs my-1 flex gap-4'>
        <div className='content flex-3 flex flex-col gap-4'>
          <div className='bg-white p-4 rounded-sm'>
            <SuperInput className={`w-full!`} value={blog?.title} state={true} handleChange={(value) => changeHandle('title', value)} placeholder='请输入页面标题' label='标题' />
            <SuperInput className={`w-full!`} value={blog?.description} state={true} multiline={true} handleChange={(value) => changeHandle('description', value)} placeholder='请输入页面描述' label='描述' />
          </div>
          <div className='bg-white p-4 rounded-sm'>
            <SuperInput className={`w-full!`} value={blog?.slug} state={true} handleChange={(value) => changeHandle('slug', value)} placeholder='请输入页面别名' label='别名（用于搜索引擎优化，不填写会自动生成）' />
            <SuperInput className={`w-full!`} value={blog?.meta_title} state={true} handleChange={(value) => changeHandle('meta_title', value)} placeholder='请输入Meta标题' label='Meta标题（用于搜索引擎优化）' />
            <SuperInput className={`w-full!`} value={blog?.meta_description} state={true} handleChange={(value) => changeHandle('meta_description', value)} placeholder='请输入Meta描述' label='Meta描述（用于搜索引擎优化）' />
            <SuperInput className={`w-full!`} value={blog?.slug && `${window && window.location.origin}/blogs/${blog.slug}`} state={false} handleChange={(value) => changeHandle('url', value)} label='访问链接' />
          </div>
        </div>
        <div className='silder flex-1 bg-white p-4 rounded-sm h-fit sticky top-[64px]'>
          <SuperCheckbox className={`w-full!`} value={blog?.status} state={true} checked={blog?.status === 0 ? true : false} onChange={(value) => changeHandle('status', value ? 0 : 1)} label='状态' />
          <SuperSelect className={`w-full!`} value={blog?.template} state={true} onChange={(value) => changeHandle('template', value)} label={'模板'} placeholder='选择模板' options={blog?.templates || []} />
          <ImageUpload value={blog?.cover} state={true} handleChange={(value) => changeHandle('cover', value)} placeholder='上传封面图片' label='封面图片' />
          <SuperInput className={`w-full!`} value={blog?.created_at && new Date(blog?.created_at).toLocaleString()} state={false} handleChange={(value) => changeHandle('created_at', value)} placeholder='创建时间' label='创建时间' />
          <SuperInput className={`w-full!`} value={blog?.updated_at && new Date(blog?.created_at).toLocaleString()} state={false} handleChange={(value) => changeHandle('updated_at', value)} placeholder='创建时间' label='创建时间' />
        </div>
      </div>
    </div>
  )

  return (<div> {loaded ? content : <Loading />} </div>)
}
